<?php

namespace yunj\app\admin\validate\auth;

use yunj\app\admin\validate\Validate;
use yunj\core\builder\YunjForm;

class AuthValidate extends Validate {

    protected function handleData(array &$data, $scene): void {
        switch ($scene) {
            case 'AuthFormSubmit':
                $this->handleDataByAuthFormSubmit($data);
                break;
        }
    }

    private function handleDataByAuthFormSubmit(&$data): void {
        /** @var YunjForm $builder */
        $builder = $data['builder'];
        $loadValues = $builder->getLoadValues();
        $currTime = time();
        $dbData = [
            // 添加子权限parent默认初始传入
            'parent' => $data['is_add_child'] ? $loadValues['parent'] : $data['parent'],
            'name' => $data['name'],
            'desc' => $data['desc'],
            'type' => $data['type'],
            'icon' => $data['icon'],
            'page_open' => $data['page_open'],
            'request_type' => $data['request_type'],
            'request_id' => $data['request_id'] ?: null,    // 唯一索引不允许空字符串
            'request_url' => $data['request_url'],
            'last_update_time' => $currTime
        ];
        if ($data['is_edit']) {
            // 编辑
            $dbData['key'] = $loadValues['key'];
            $dbData['parent'] = $data['parent'];
        } else {
            // 新增
            // 判断是否存在
            $hasExist = self::getAdminAuthModel()->getOwnCount([
                ['key', '=', $data['key']],
            ]);
            if ($hasExist) {
                throw_error_json("KEY[{$data['key']}]已存在");
            }
            $dbData['key'] = $data['key'];
            $dbData['create_time'] = $currTime;
        }
        $data['dbData'] = $dbData;
    }

}